﻿using System;
using System.Web.Mvc;
using ProjetoComperio.BusinessLogicLayer;
using ProjetoComperio.DataLayer.Entities;
using ProjetoComperio.Framework.Web.Security.UrlEncrypt;
using ProjetoComperio.Presentation.Web.Models;
using ProjetoComperio.SystemFramework.Extensions;
using ProjetoComperio.SystemFramework.Web;
using System.Web;
using System.IO;
using ProjetoComperio.Framework.Web.Security.HtmlMessages;
using ProjetoComperio.Framework.Configuration;
using ProjetoComperio.Framework.Web.Mail;

namespace ProjetoComperio.Presentation.Web.Controllers
{
    public class ContributionController : ComperioController
    {
        private ContributionBLL contributionBLL;
        private ContributionItemBLL contributionItemBLL;
        private AcademicPersonBLL academicPersonBll;


        public ContributionBLL ContributionBLL
        {
            get
            {
                if (contributionBLL == null)
                    contributionBLL = new ContributionBLL();

                return contributionBLL;
            }
        }


        public ContributionController()
        {
            academicPersonBll = new AcademicPersonBLL();
            contributionItemBLL = new ContributionItemBLL();
        }

        [HttpGet]
        public ActionResult AddAcademicPerson()
        {
            Session["AcademicOrganizations"] = ContributionBLL.RetrieveAcademicPersonContributions(Convert.ToInt32(this.CurrentUser.PersonID));
            return View();
        }
        [HttpPost]
        public ActionResult AddAcademicPerson(AddAcademicPerson addAcademicPerson)
        {
            if (!ModelState.IsValid)
                return View();

            AcademicPersonBLL academicPersonBll = new AcademicPersonBLL();
            academicPersonBll.RegisterAcademicPersonInContribution(addAcademicPerson.ContributionID, Convert.ToInt32(this.CurrentUser.PersonID));
            return View();
        }

        [HttpGet]
        public ActionResult ListAcademicPeople()
        {
            var contributions = ContributionBLL.RetrieveAcademicPersonContributions(Convert.ToInt32(this.CurrentUser.PersonID));
            Session["contributions"] = contributions.ToSelectedItemList<Contribution>(ao => ao.ContributionID, ao => ao.Title);
            return View(new ListAcademicPeople());
        }
        [HttpPost]
        public ActionResult ListAcademicPeople(FormCollection form)
        {
            academicPersonBll.RetrieveAcademicPeopleInContribution(Convert.ToInt32(form["ContributionID"]));
            ListAcademicPeople listAcademicPeopleModel = new ListAcademicPeople();
            listAcademicPeopleModel.PeopleInProject = academicPersonBll.RetrieveAcademicPeopleInContribution(Convert.ToInt32(form["ContributionID"]));
            return View(listAcademicPeopleModel);

        }


        public ActionResult EnableContribution(string id)
        {
            var contributionID = Convert.ToInt32(URLEncrypt.DecryptFromString(id));
            ContributionBLL.EnableContribution(contributionID);
            ViewData["Title"] = ContributionBLL.RetrieveContribution(contributionID).Title;

            return View();
        }


        public ActionResult DownloadFile()
        {
            return new DownloadResult("~/Uploads")
            {
                FileDownloadName = "firefox.exe"
            };

        }



        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UploadFile()
        {
            foreach (string inputedFile in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[inputedFile];

                if (file.ContentLength > 0)
                {
                    file.SaveAs(Path.Combine(HttpContext.Server.MapPath("../Uploads"), Path.GetFileName(file.FileName)));
                }

                var contributionItem = new ContributionItem
                {
                    ContributionID = Convert.ToInt32(URLEncrypt.DecryptFromString(Session["id"].ToString())),
                    FileName = file.FileName,
                    FileUrl = Path.Combine(HttpContext.Server.MapPath("../Uploads"), Path.GetFileName(file.FileName)),
                    UploadDate = DateTime.Now,
                    UserName = "UserNameDefault"
                };

                contributionItemBLL.Create(contributionItem);
            }

            return Redirect(Request.UrlReferrer.ToString());
        }

        public void SendNotificationToComperioAdmin(Contribution contribution)
        {
            var htmlMessage = HtmlMessageUtility.GetHtmlMessage(HtmlMessageUtility.Messages.ENABLECONTRIBUTION, this.GetType());

            htmlMessage.InsertContent("UserName", contribution.AcademicPerson.Name)
                .InsertContent("RegisterDate", contribution.RegisterDate.ToString("dd/MM/yyyy hh:mm"))
                .InsertContent("UrlToEnableContribution", ConfigurationLoader.LoadValue(ConfigurationLoader.Keys.COMPERIOURL) + "/Contribution/EnableContribution/" + URLEncrypt.EncryptToString(contribution.ContributionID.ToString()));

            MailSender.SendMail(ConfigurationLoader.LoadValue(ConfigurationLoader.Keys.COMPERIOADMINEMAIL), "Um novo cadastro de contribuição foi realizado", "TESTEE EMAIL");
        }


    }
}
